// https://www.lintcode.com/problem/minimum-difference-between-bst-nodes/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the root
     * @return: the minimum difference between the values of any two different nodes in the tree
     */
    public int minDiffInBST(TreeNode root) {
        // Write your code here
        List<Integer> list = new ArrayList<>();
        buildList(root, list);
        int ret = list.get(1) - list.get(0);
        for (int i = 2; i < list.size(); ++i) {
            int diff = list.get(i) - list.get(i - 1);
            if (diff < ret) {
                ret = diff;
            }
        }
        return ret;
    }
    
    protected void buildList(TreeNode root, List<Integer> list) {
        if (root != null) {
            buildList(root.left, list);
            list.add(root.val);
            buildList(root.right, list);
        }
    }
}